package com.chinawayltd.ews.sample.web.system;

import com.chinawayltd.ews.sample.manager.redis.TokenCacheManager;
import com.chinawayltd.ews.sample.util.CookiesUtil;
import com.chinawayltd.ews.sample.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: greeProject
 * @description:
 * @author: xiazj
 * @create: 2018-05-15 16:57
 **/
@RestController
public class TokenTransmitController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SET_TOKEN_FUNCTION = "setUserToken";

    @Autowired
    private TokenCacheManager tokenCacheManager;

    /**
     * 回调方法，必须存在，建议将token保存在cookie当中，因为cookie的有效期是5分钟有可能比session长，
     * 避免个别情况session超时了但是cookie还没有过期的情况
     * */
    @RequestMapping("/inside.php")
    public String loginCallback(@RequestParam("f") String function, @RequestParam("_TOKEN") String token,
                                HttpServletRequest request, HttpServletResponse response) {
        try {
            if (SET_TOKEN_FUNCTION.equals(function)) {
                if(StringUtils.isNotBlank(token)){
                    //给浏览器设置cookie,后续通过拦截器去不断刷新redis缓存里面token对应的用户信息
                    CookiesUtil.setCookie(response,  CookiesUtil.TOKEN_KEY_STRING, token,  CookiesUtil.TOKEN_VALID_TIME);
                }else{
                    //清理缓存中的token对应的用户信息
                    String oldToken = CookiesUtil.getCookieByName(request, CookiesUtil.TOKEN_KEY_STRING);
                    if(StringUtils.isNotBlank(oldToken))tokenCacheManager.deleteUserByToken(oldToken);
                    //注销用户浏览器的cookies
                    CookiesUtil.clearCookie(request, response, CookiesUtil.TOKEN_KEY_STRING);
                }
            }
        } catch (Exception e) {
            logger.error("token回传出现异常：", e);
        }
        return "OK";
    }

}
